#include "SerialPortClient.h"


namespace CommonComponet
{
	SerialPortClient::SerialPortClient(QSharedPointer<SerialInfo> serical_info, DEVICE_CONN_TYPE comtype, QObject* parent)
		: QObject(parent)
	{
		m_serical_info = serical_info;
		m_connState = DeviceConnState::UnconnectedState;
		m_ComType = comtype;
	}

	SerialPortClient::~SerialPortClient()
	{
		//
	}

	void SerialPortClient::Started()
	{
		if (!m_serical_info)
			return;

		m_port = new QSerialPort(this);

		if (m_ComType == ASYNC)
		{
			// connect(m_port, &QSerialPort::readyRead, this, &SerialPortClient::recv_device_data);
			m_ASYNC_timer = new QTimer(this);
			QObject::connect(m_ASYNC_timer, &QTimer::timeout,this, &SerialPortClient::recv_device_data);
			m_ASYNC_timer->setInterval(50); 
		}
		m_port->setPortName(m_serical_info->comPort);
		m_port->setBaudRate(m_serical_info->baudRate);
		m_port->setDataBits(static_cast<QSerialPort::DataBits>(m_serical_info->dataBits));
		m_port->setParity(static_cast<QSerialPort::Parity>(m_serical_info->parity));
		m_port->setStopBits(static_cast<QSerialPort::StopBits>(m_serical_info->stopBits));
		m_port->setFlowControl(QSerialPort::NoFlowControl);
		if (!m_port->open(QIODevice::ReadWrite))
		{
			m_connState = DeviceConnState::UnconnectedState;
		}
		else
		{
			m_port->clear();
			m_port->clearError();
			//m_port->setRequestToSend(true);             //设置 RTS 为高电平
			m_port->setDataTerminalReady(true);         //设置 DTR 为高电平
			m_connState = DeviceConnState::ConnectedState;

			if (m_ASYNC_timer)
			{
				m_ASYNC_timer->start();
			}
		}

		emit sig_connection_state(m_connState);
	}

	void SerialPortClient::slot_async_timeout_send_message(QString message, int write_timeout, int read_timeout) //waiting async message
	{
		if (!m_port) return;

		if (m_ComType != ASYNC_AND_TIME_OUT)
			return;

		if (m_working)
		{
			qDebug() << "!!!Error 串口正在使用中。。";
			emit sig_receiveDataFromServer("ComInUse");
			return;
		}

		m_working = true;
		m_timer_out = 0;
		m_com_data = "";

		QByteArray readData_temp = m_port->readAll();

		m_com_data = "";
		m_port->write(message.toUtf8());
		if (m_port->waitForBytesWritten(write_timeout))
		{
			bool readTimeout = m_port->waitForReadyRead(read_timeout);

			QTimer::singleShot(300, this, &SerialPortClient::readPortDataTimer);

			m_timer_out = m_timer_out + 300;
		}
		else
		{
			emit sig_receiveDataFromServer(QString("PortWriteError"));

			m_working = false;
			m_com_data = "";
			m_timer_out = 0;
		}
	}

	void SerialPortClient::readPortDataTimer()
	{
		if (!m_port) return;

		QByteArray data = m_port->readAll();
		QString sub_value = data;
		m_com_data = m_com_data + sub_value;

		if (m_com_data.contains("\n"))
		{
			qDebug() << "总耗时:" << m_timer_out << " 数据:" << m_com_data;

			emit sig_receiveDataFromServer(m_com_data.trimmed());

			m_timer_out = 0;
			m_com_data = "";
			m_working = false;
		}
		else
		{
			if (m_timer_out > 3000)
			{
				emit sig_receiveDataFromServer(m_com_data.trimmed());

				m_timer_out = 0;
				m_com_data = "";
				m_working = false;
			}
			else
			{
				m_timer_out = m_timer_out + 400;
				QTimer::singleShot(400, this, &SerialPortClient::readPortDataTimer);
			}

		}
	}

	QString SerialPortClient::slot_send_and_wait_message(QString message, int write_timeout, int read_timeout)
	{
		if (!m_port) return "";

		if (m_ComType != SYNC_FAQ_WAIT)
			return "";

		m_port->readAll();
		m_port->write(message.toUtf8());
		if (m_port->waitForBytesWritten(write_timeout))
		{
			m_port->waitForReadyRead(500);

			QByteArray readData = m_port->readAll();
			return readData.trimmed();
		}
		else
		{
			qDebug() << "串口发送命令超时";
		}

		m_working = false;
		m_com_data = "";
		m_timer_out = 0;
		return "Write ERROR";
	}

	void SerialPortClient::slot_Reconnect(const QString& comport)
	{
		if (m_ASYNC_timer)
		{
			m_ASYNC_timer->stop();
		}

		if (!m_port)
			return;

		if (comport != m_serical_info->comPort)
			m_serical_info->comPort = comport;

		m_port->close();

		m_port->setPortName(m_serical_info->comPort);
		m_port->setBaudRate(m_serical_info->baudRate);
		m_port->setDataBits(static_cast<QSerialPort::DataBits>(m_serical_info->dataBits));
		m_port->setParity(static_cast<QSerialPort::Parity>(m_serical_info->parity));
		m_port->setStopBits(static_cast<QSerialPort::StopBits>(m_serical_info->stopBits));
		m_port->setFlowControl(QSerialPort::NoFlowControl);

		if (!m_port->open(QIODevice::ReadWrite))
		{
			m_connState = DeviceConnState::UnconnectedState;
		}
		else
		{
			m_port->clear();
			m_port->clearError();
			//m_port->setRequestToSend(true);             //设置 RTS 为高电平
			m_port->setDataTerminalReady(true);         //设置 DTR 为高电平
			m_connState = DeviceConnState::ConnectedState;

			if (m_ASYNC_timer)
			{
				m_ASYNC_timer->start();
			}
		}

		emit sig_connection_state(m_connState);

		m_working = false;
		m_timer_out = 0;
		m_com_data = "";
	}

	void SerialPortClient::slot_send_message(QString message) //waiting async message
	{
		if (!m_port) return;

		if (m_ComType != ASYNC)
			return;

		m_port->readAll();
		m_port->write(message.toUtf8());
	}

	void SerialPortClient::recv_device_data()
	{
		if (!m_port) return;

		if (!m_port->isOpen()) return;

		m_port->waitForReadyRead(100);
		
		QByteArray readData = m_port->readLine();

		QString content = QString(readData);
		if (content.isEmpty())
			return;

		qDebug() << content;

		QStringList subcontentlist = content.split("\r\n");
		for (auto& subcontent : subcontentlist)
		{
			if (subcontent.trimmed().isEmpty())
				continue;

			qDebug() << subcontent;
			emit sig_receiveDataFromServer(subcontent.trimmed());

			break;
		}
		

		m_port->clear();

		m_working = false;
		m_timer_out = 0;
		m_com_data = "";
	}
}
